package com.sali.handler;

import com.sali.config.MockConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/21 下午11:17.
 * @version: 1.0
 */
@Component
@Slf4j
public class DataHandler {

    @Autowired
    private MockConfig mockConfig;

    @Autowired
    private SocketHandler socketHandler;

    @Autowired
    @Qualifier("commonExecutor")
    private ExecutorService executorService;

    public void send(String data) {
        if (StringUtils.isEmpty(data)) {
            log.error("文件错误,请检查配置文件路径是否合法");
            System.exit(1);
        }
        // 假设 count = 50，dbSplitSize = 10
        int count = mockConfig.getCount();
        int dbSplitSize = mockConfig.getDbSplitSize();
        if (count > dbSplitSize && mockConfig.isEnable()) {
            // total = (50 + 10 - 1) / 10 = 59 / 10 = 5
            int total = (count + dbSplitSize - 1) / dbSplitSize;
            CountDownLatch countDownLatch = new CountDownLatch(total);
            for (int pageSize = 1; pageSize <= total; pageSize++) {
                // (第一批次)yushu = count - ((pageSize - 1) * dbSplitSize) = 50 - ((1 - 1) * 10) = 50
                int yushu = count - ((pageSize - 1) * dbSplitSize);
                if (yushu >= dbSplitSize) {
                    // (第一批次)走这里
                    executorService.execute(() -> this.dataHandel(data, dbSplitSize, countDownLatch));
                } else {
                    executorService.execute(() -> this.dataHandel(data, yushu, countDownLatch));
                    break;
                }
            }

            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                log.error("countDownLatch 抛出异常,异常原因:{}", e.getMessage());
                Thread.currentThread().interrupt();
            }
        } else {
            //串行处理
            this.dataHandel(data, count);
        }
    }


    /**
     * description: 数据发送
     **/
    public void dataHandel(String data, int count) {
        dataHandel(data, count, null);
    }

    /**
     * description: 数据发送
     **/
    public void dataHandel(String data, int count, CountDownLatch countDownLatch) {
        long startTime = System.currentTimeMillis();
        List<String> datas = this.handle(data, count);
        long endTime = System.currentTimeMillis();
        log.info("数据镜像结束共耗时：{}", (endTime - startTime));
        socketHandler.handle(datas);
        long socketEndTime = System.currentTimeMillis();
        log.info("数据发送结束共耗时：{}", (socketEndTime - endTime));
        if (countDownLatch != null) {
            countDownLatch.countDown();
            log.info("本批次已完成处理，还剩下{}批次", countDownLatch.getCount());
        }
    }
    
    /**
    * description: 将数据进行镜像复制
    **/
    private List<String> handle(String data, int count) {
        if (StringUtils.isEmpty(data)) {
            log.warn("镜像数据源为空，请检查指定文件是否合法！！");
            return Collections.emptyList();
        }
        log.info("正在准备镜像数据,本次共计划复制{}份", count);

        String[] datas = new String[count];
        Arrays.fill(datas, data);
        return Arrays.asList(datas);
    }

}
